<?php

defined('BY_JYA') or exit('error');
$_RQ['op']=$_RQ['op']?:'main';
$activity_tables=array(
		'goods'=>'jy_weishop_coupon_goodsendtask',
		'order'=>'jy_weishop_coupon_sendtasks',
		'new'=>'jy_weishop_coupon_sendticket',
		'huodong'=>'jy_weishop_coupon_huodongsendtask',
		'use'=>'jy_weishop_coupon_usesendtasks',
);
if($_RQ['op']=='main'){
	//展示获得的活动卡券
	$id=intval($_RQ['id']);
	//获取所有同类优惠券
	$gives=pdo_getall('jy_weishop_coupon_wait',array('nolook >'=>0,'mid'=>$_SESSION['uid']));
	$couponids=array();
	foreach($gives as $gv){
		$activity=pdo_get($activity_tables[$gv['ac_type']],array('uniacid'=>$_SESSION['uniacid'],'id'=>$gv['ac_id']));
		if($activity['couponid']){
			if(strpos($activity['couponid'], ';') !== false){
				$newcouponids=str_array($activity['couponid']);
				foreach($newcouponids as $cv){
					$couponids[]=$cv;
				}
			}else{
				$couponids[]=$activity['couponid'];
			}
		}
	}
	if(!empty($couponids)){
		$coupons=pdo_getall('jy_weishop_coupon',array('uniacid'=>$_SESSION['uniacid'],'id'=>$couponids));
	}
	$list=array();
	foreach($coupons as $k=>$v){	
		$coupon=model('jy_weishop/coupon')->intcoupon($v['id']);
		if($coupon['id']){
			$coupon['limittimes']['tstart']=date('Y/m/d',$coupon['limittimes']['tstart']);
			$coupon['limittimes']['tend']=date('Y/m/d',$coupon['limittimes']['tend']);
			$list[]=array('coupon'=>$coupon);
		}
	}
	$return['coupons']=$list;
	pdo_update('jy_weishop_coupon_wait',array('nolook'=>0),array('nolook >'=>0,'mid'=>$_SESSION['uid']));
	exi($return);
}
if($_RQ['op']=='post'){
	//领取活动获得的卡券
	$post=get_postdata();
	$id=intval($post['id']);
	$give=pdo_get('jy_weishop_coupon_wait',array('id'=>$id));
	if(!$give){
		exi('活动不存在！','error');
	}
	if($give['status']==1){
		exi('您已经领取过了！','error');
	}
	//获取所有同类优惠券
	$gives=pdo_getall('jy_weishop_coupon_wait',array('status'=>0,'mid'=>$_SESSION['uid'],'ac_type'=>$give['ac_type'],'ac_id'=>$give['ac_id']));
	$table=$activity_tables[$give['ac_type']];
	$activity=pdo_get($table,array('id'=>$give['ac_id']));
	if(isset($activity['num']) && $activity['num']<$activity['sendnum']){
		exi('卡券已经被领完啦，下次早点哦！','error');
	}
	$couponids=array();
	foreach($gives as $gv){
		if($activity['couponid']){
			if(strpos($activity['couponid'], ';') !== false){
				$newcouponids=str_array($activity['couponid']);
				foreach($newcouponids as $cv){
					$couponids[]=$cv;
				}
			}else{
				$couponids[]=$activity['couponid'];
			}
		}			
	}
	$sendnum=$activity['sendnum']?:1;
	foreach($couponids as $couponid){
		for($i=0;$i<$sendnum;$i++){
			model('jy_weishop/coupon')->getcoupon($couponid);
		}
	}
	pdo_update('jy_weishop_coupon_wait',array('status'=>1),array('status'=>0,'mid'=>$_SESSION['uid'],'ac_type'=>$give['ac_type'],'ac_id'=>$give['ac_id']));
	if(isset($activity['num']) && $sendnum){
		pdo_update($table,array('num -='=>$sendnum),array('id'=>$activity['id']));
	}
	$menus_index='jy_merch/merch//merchid'=>$_SESSION['merchid'];
	exi('优惠券领取成功！','',$menus_index);
}
